package com.jy.appmarket.screenlock.utils;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.jy.appmarket.screenlock.database.CustomMessageTb;
import com.jy.appmarket.utils.LogUtil;

import android.content.Context;

public class CustomMessageUtils {
	private static final String TAG = CustomMessageUtils.class.getName();
	/**
	 * 默认开启消息提醒
	 */
	public static final int DEFAULT_APP = 0;
	/**
	 * 快捷启动的固定类型
	 */
	public static final int FIXED_APP = 1;

	public static class CustomMessage {
		private ArrayList<CustomMessageTb> defaultList; // 默认开启消息提醒列表
		private ArrayList<CustomMessageTb> fixedList; // 固定开启消息提醒列表

		public ArrayList<CustomMessageTb> getDefaultList() {
			return defaultList;
		}

		public void setDefaultList(ArrayList<CustomMessageTb> defaultList) {
			this.defaultList = defaultList;
		}

		public ArrayList<CustomMessageTb> getFixedList() {
			return fixedList;
		}

		public void setFixedList(ArrayList<CustomMessageTb> fixedList) {
			this.fixedList = fixedList;
		}

	}

	public static List<CustomMessageTb> initCustomMessageDB(Context context) {
		Gson gson = new Gson();
		String json = getFromAssets(context, "custom_message");
		CustomMessage cmt = null;
		try {
			cmt = gson.fromJson(json, CustomMessage.class);
		} catch (Exception e) {
			LogUtil.w(TAG, "init failed ", e);
		}
		if (cmt == null) {
			return null;
		}
		ArrayList<CustomMessageTb> list = new ArrayList<CustomMessageTb>();

		ArrayList<CustomMessageTb> tmp = cmt.getFixedList();
		if (tmp != null) {
			for (CustomMessageTb s : tmp) {
				s.setType(FIXED_APP);
			}
			list.addAll(cmt.getFixedList());
		}

		tmp = cmt.getDefaultList();
		if (tmp != null) {
			for (CustomMessageTb s : tmp) {
				s.setType(DEFAULT_APP);
			}
			list.addAll(cmt.getDefaultList());
		}
		return list;
	}

	public static List<CustomMessageTb> initFixedAppDB(Context context) {
		try {
			Gson gson = new Gson();

			String json = getFromAssets(context, "custom_message");
			CustomMessage cm = gson.fromJson(json, CustomMessage.class);
			if (cm == null) {
				return null;
			}
			ArrayList<CustomMessageTb> fixList = cm.getFixedList();
			if (fixList == null || fixList.size() == 0) {
				return null;
			}

			for (CustomMessageTb s : fixList) {
				s.setType(FIXED_APP);
			}
			return cm.getFixedList();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String getFromAssets(Context context, String fileName) {
		String result = "";
		try {
			InputStream in = context.getResources().getAssets().open(fileName);
			byte[] buffer = new byte[in.available()];
			in.read(buffer);
			result = new String(buffer, "UTF-8");
		} catch (Exception e) {
			LogUtil.w(TAG, "failed to open asset " + fileName);
		}
		return result;
	}
}
